// pages/admin/order/order.js
const app = getApp()
Page({
  data: {
    active:2,
    tabList: ["全部", "待接单", "待配送", "配送完毕","已收货"],
    items:[],
    filterData:'',
    serverHost: app.config.serverHost
  },
  //分类数据
  changeActive: function (a) {
    let item = this.data.filterData
    let i = item.filter(e => {
      return a.detail.title == '全部' ? item : e.a_status == a.detail.title
    })
    if(a.detail.title == '待配送'){
      this.setData({
        isbutton:true
      })
    }else{
      this.setData({
        isbutton: false
      })
    }
    this.setData({
      items: i
    })
  },
  //跳转页面
  onChange(event) {
    if (event.detail == "0") {
      wx.redirectTo({
        url: '../index',
      })
    } else if (event.detail == "1") {
      wx.redirectTo({
        url: '../Goodslist/index',
      })
    } else if (event.detail == "3") {
      wx.redirectTo({
        url: '../my/my',
      })
    }
  },
  onLoad() {
    app.api.getData('admin/order','none',(res) => {
      new Promise((resolve,reject)=>{
        let data = res.data.reverse()
        data.filter(item=>{
          item.order_time = app.util.formatTime(item.order_time)
        })
        this.setData({
          items:res.data,
          filterData:this.data.items
        })
        resolve(res.data)
      })
      .then(data=>{
        this.setData({
          filterData: data
        })
      })
    })
  },
  // 打印订单
  dayin(e){
    let id = e.currentTarget.dataset.id
    let items = this.data.items
    items.filter(item=>{
      if(item._id == id){
        app.api.post('web/getorderexcel', item, (res) => {})
      }
    })
  },
  // 接单
  jiedan(e){
    var that = this;
    wx.showModal({
      title: '接单或配送',
      content: '确认修改订单信息吗？',
      success: function (res) {
        if (res.confirm) {
          let a = e.currentTarget.dataset.status
          let _id = e.currentTarget.dataset.id
          let a_status = a == "待接单" ? "待配送" : "配送完毕"
          let items = that.data.items
          app.api.updateData('admin/order', { _id: _id, a_status: a_status }, res => {
            items.forEach(item => {
              if(item._id == _id){
                if(item.a_status == '待接单'){
                  let pu = []
                  item.goods_list.filter(a=>{
                    pu.push({goods:a.id.name,value:a.value})
                  })
                  let bod = {
                    address:item.address[0].local,
                    time:new Date().toISOString().split('T')[0],
                    goodslist:pu
                  }
                  app.api.post('admin/bill',bod,res=>{})
                }
                item.a_status = a_status
              }
            })
            that.setData({
              items: items
            })
          })
          wx.showToast({
            title: '修改成功',
            duration: 500,      //停留时间
          })
        }
      }
    })
  }
})